<template>


<!--marked 转译为html -->
  <div class="page">
    <div class="page_top ai-margin-bottom ai-border-bottom">
      <div class="ai-margin-lr left">
        <i class="el-icon-menu" style="font-size: 24px"></i>
        <span class="ai-margin-left-sz title">{{name}}</span>
      </div>
      <div class="right">
        <div class="ai-padding ai-display-ib">
          <el-link @click="returnSuperior">返回<i class="el-icon-right el-icon--right"></i></el-link>
        </div>
      </div>
    </div>
    <div class="page_bottom">
      <el-form class="flex-column" :model="form" label-width="80px">
        <div class="flex-row">
          <div class="flex-column">
            <el-form-item label="标题" required>
              <el-input v-model="form.title" style="width: 200px" size="medium" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="设备类型" required>
              <el-select v-model="form.type" placeholder="请选择">
                <el-option
                  v-for="item in dynamicTags"
                  :key="item.id"
                  :label="item.type"
                  :value="item.type">
                </el-option>
              </el-select>
              <!--                    <el-input v-model="form.type" placeholder="请输入设备类型"></el-input>-->
            </el-form-item>
          </div>
          <el-form-item class="img-box" label="封面图片" required>
            <div class= " ai-display-ib ai-margin-right-sz" v-for="(item, index) in photo" :key="index"
                 v-show="photo.length !== 0">
                  <span class="dimback" @mouseenter="mouseenterImage(index)" @mouseleave="mouseleaveImage">
                      <img class="images" :src="item" alt="">
                      <i class="el-icon-delete dimIcon" @click="handleDeleteImage(index)"
                         v-show="val === index"></i>
                  </span>
            </div>
            <el-upload  action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false"
                       list-type="picture-card" :http-request="handleUpload" :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </div>

        <el-form-item label="教程内容" required>
          <!--          <vue-ueditor-wrap id="contUeditor" v-model="form.content" :config="config" />-->
          <mavon-editor
            class="markdown-body"
            :toolbars="toolbars"
            v-model="form.content"
            @imgAdd="handleEditorImgAdd"
            @imgDel="handleEditorImgDel"
            style="height:600px"
            @change="change"
            :boxShadow="false"
            :subfield="subfield"
            defaultOpen="preview"
            ref=md
            codeStyle="atelier-lakeside-dark"
          />

        </el-form-item>
      </el-form>
      <div class="dialog-footer ai-margin-top-lg ai-text-align-right">
        <!--                <el-button >取消</el-button>-->
        <el-button type="primary" @click="handleSave">{{courseTitle}}</el-button>
      </div>
    </div>

  </div>
</template>

<script>
  import { addCodeBtn } from '../../styles/markdown/mavon'
  import 'highlight.js/styles/googlecode.css'
  import hljs from 'highlight.js'
  hljs.highlightCode = function () {
    //自定义highlightCode方法，将只执行一次的逻辑去掉
    let blocks = document.querySelectorAll('pre code');
    [].forEach.call(blocks, hljs.highlightBlock);
  };

  import {
    addProblem,
    getProblemById,
    problemUploadImg,
    updateProblem,
    updateProblemByContent
  } from "../../api/problem";
  import {getEquipmentType} from "../../api/equipment";
  export default {
    name: "MarkdownEditor",
    data() {
      return {
        //markdown是否分栏
        subfield:false,
        loading: false,
        name: "添加维护教程",
        courseTitle: "添加",
        dialogCourse: true,
        form: {
          id: "",
          content: "",
          title: "",
          type: "",
          createTime: "",
          photo: ""
        },
        courseID: "",
        state: "",
        photo: [],
        image: [],
        formValue: "",
        val: "-1",
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: true, // 标记
          superscript: true, // 上角标
          subscript: true, // 下角标
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: true, // 图片链接
          code: true, // code
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: true, // 沉浸式阅读
          htmlcode: true, // 展示html源码
          help: true, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: true, // 下一步
          trash: true, // 清空
          save: true, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: true, // 导航目录
          /* 2.1.8 */
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          /* 2.2.1 */
          subfield: true, // 单双栏模式
          preview: true, // 预览
        },
        dynamicTags: [],
        mdContent:''
      }
    },
    mounted() {
      hljs.highlightCode()
      this.$nextTick(_ => {
        addCodeBtn()
      })
      this.state = this.$router.history.current.query.state;
      if (Number(this.state) === 1) {
        this.name = "添加维护教程";
        this.courseTitle = "添加";
        this.dialogCourse = true;
        this.subfield = true;
      } else if (Number(this.state) === 2) {
        this.name = "编辑维护教程";
        this.courseTitle = "保存";
        this.dialogCourse = false;
        this.formValue = JSON.parse(this.$router.history.current.query.data)
        this.handleContent();
      }
      this.handleRepairsContent();
    },
    methods: {


      //监听markdown变化
      change(value, render) {
        // console.log(value)
        // console.log(render)
        this.form.content = render;
        console.log(this.form.content)
        // this.mdContent = value;
      },
      //上传图片接口pos 表示第几个图片
      handleEditorImgAdd(pos , $file){
        var formdata = new FormData();
        formdata.append('file[]' , $file);
        problemUploadImg(formdata)
          .then(res => {
            var url = res.result.url[0].file;
            console.log(res.result.url[0].file)
            this.$refs.md.$img2Url(pos, url);  //这里就是引用ref = md 然后调用$img2Url方法即可替换地址
          });
      },
      handleEditorImgDel(){
        console.log('handleEditorImgDel');    //我这里没做什么操作，后续我要写上接口，从七牛云CDN删除相应的图片
      },


      /**
       * 获取教程
       */
      handleContent() {
        console.log(this.formValue.id)

        getProblemById(this.formValue.id)
          .then(rsp => {
            console.log(rsp)
            this.form = rsp.result;
            // this.form.type = Number(this.form.type)
            if (this.form.photo !== null && this.form.photo !== undefined && this.form.photo !== "") {
              this.photo.push(this.form.photo)
            }
          })
          .catch(respond => {
            console.log(respond)
          })
      },

      /**
       * 获取设备类型
       */
      handleRepairsContent() {
        getEquipmentType()
          .then(rsp => {
            console.log(rsp)
            this.dynamicTags = rsp.result;
          })
          .catch(respond => {
            console.log(respond)
          })
      },

      /**
       * 保存、编辑
       */
      handleSave() {
        let _this = this;
        console.log(_this.form)
        if (_this.photo.length > 1) {
          _this.$message.warning("只能有一张图片")
        } else {
          _this.form.photo = this.photo.join()
          if (_this.dialogCourse) {
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            setTimeout(() => {
              const params = new URLSearchParams();
              params.append('content', _this.form.content)
             addProblem({title:_this.form.title,type:_this.form.type,photo:_this.form.photo}, {content:_this.form.content})
                .then(rsp => {
                  console.log(rsp)
                  _this.$message.success(rsp.msg);
                  this.$router.push('/MaintenanceTutorial/index')
                })
                .catch(respond => {

                })
              loading.close();
            }, 2000);
          } else {
            const params = new URLSearchParams();
            let data = '';
            if (this.form.title !== this.formValue.title) {
              data = `${data}title=${_this.form.title}&`;
            }
            if (this.form.type !== this.formValue.type) {
              data = `${data}type=${_this.form.type}&`;
            }
            if (this.form.photo !== this.formValue.photo) {
              data = `${data}photo=${_this.form.photo}&`;
            }
            if (this.form.content !== this.formValue.content) {
              params.append('content', _this.form.content)
              _this.handleEditorContent({content: _this.form.content}, _this.form.id)
              // _this.handleEditorContent({content: _this.$refs.md.d_render}, _this.form.id)
            }
            data = data.substring(0, data.length - 1)
            console.log(data)
            console.log(data)
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            setTimeout(() => {
              console.log(data)
              updateProblem(_this.form.id,data, {content:params.get("content")})
                .then(rsp => {
                  console.log(rsp)
                  _this.$message.success(rsp.msg);
                  this.$router.push('/MaintenanceTutorial/index')
                })
                .catch(respond => {
                  _this.$message.warning(respond.msg);
                })
              loading.close();
            }, 2000);

          }
          ;
        }
        ;
      },
      handleEditorContent(params, id) {
        updateProblemByContent(id, params)
          .then(rsp => {
            console.log(rsp)
          })
          .catch(respond => {
            console.log(respond)
          })
      },
      handleDeleteImage(index) {
        this.photo.splice(index, 1)
      },
      handleUpload(objects) {
        let obj = objects.file;
        let formData = new FormData();
        formData.append('file[]', obj);
        problemUploadImg(formData)
          .then(rsp => {
            console.log(rsp)
            let image = rsp.result.url[0].file;
            this.photo.push(image);
            console.log(this.photo)
          })
          .catch(respond => {

          })
      },//上传图片
      mouseenterImage(index) {
        this.val = index;
      },
      mouseleaveImage() {
        this.val = ""
      },
      returnSuperior() {
        this.$router.push('/MaintenanceTutorial/index')
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
        // this.image.splice(index,1)
      },
    }
  };
</script>

<style scoped lang="scss">
  .page {
    box-sizing: border-box;

    .page_top {
      display: flex;

      .left {
        flex: 1;

        .title {
          line-height: 50px
        }
      }

      .right {
        flex: 1;
        text-align: right;
      }
    }

    .page_bottom {
      width: 95%;
      margin: 40px auto;

      .dimback {
        display: inline-block;
        background: #000;
        width: 150px;
        height: 150px;
        border-radius: 6px;
        position: relative;

        .images {
          width: 150px;
          height: 150px;
          border-radius: 6px;
          border: 1px solid #c0ccda;
        }

        .dimIcon {
          width: 150px;
          height: 150px;
          display: flex;
          align-items: center;
          justify-content: center;
          position: absolute;
          top: 0;
          left: 0;
          font-size: 25px;
          color: #fff;
          cursor: pointer;
          background: rgba(101, 101, 101, 0.6);
        }
      }
    }
  }



  .img-box{
    /deep/
    .el-form-item__content{
      display: flex;
    }
  }

.markdown-body{
  pre.code {
    position: relative;
    border-radius: 3px;
    border: 1px solid #C3CCD0;
    overflow: hidden;
    padding-left: 60px!important;
    code {
      line-height: 30px!important;
    }
    ol.pre-numbering {
      position: absolute;
      top: 0;
      left: 5px;
      line-height: 30px;
      padding: 16px 0;
      list-style-type:none;
      counter-reset:sectioncounter;
      margin-bottom: 0;
      li{
        margin-top: 0!important;
        &:before{
          content:counter(sectioncounter) "";
          counter-increment:sectioncounter;
          display: inline-block;
          width: 40px;
          text-align: center;
          border-right: solid 1px rgba(0, 0, 0, 0.53);
        }
      }
    }
    i.code-copy{
      position: absolute;
      top:0;
      right: 0;
      background-color: #464d5e;
      padding: 3px;
      margin: 3px 3px 0 0;
      font-size: 11px;
      border-radius: inherit;
      color: #f1f1f1;
      cursor: pointer;
      display: none;
    }
    &:hover i.code-copy{
      display: block;
    }
  }
}
</style>
